var nullField = { "Comment": "", "ColumnName": "", "ColumsID": 0, "TypeName": "", "MaxLength": null };
var applist;
var storage;

(function ($) {
    jQuery.expr[':'].Contains = function (a, i, m) {
        return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };
}(jQuery));

function filterList(list) {
    $('#txtSearch').change(function () {
        var filter = $(this).val();
        if (filter) {
            $matches = $(list).find('h4:Contains(' + filter + ')').parent();
            $('a', list).not($matches).slideUp();
            $matches.slideDown();
        } else {
            $(list).find("a").slideDown();
        }
        return false;
    }).keyup(function () {
        $(this).change();
    }).on('paste', function () {
        setTimeout(function () {
            var name = $('#txtSearch').val();
            $("a[tablename='" + name + "']")[0].click();
        }, 100);
    });
    $('#txtSearch').val(storage["SearchText"]);
    $('#txtSearch').change();
}
$(function () {
    $.getJSON('/Home/GetTableList', function (data) {
        createVue(data);
        init();
        filterList($("#listTable"));
    });

});

function init() {
    storage = window.localStorage;
    $('#txtModelFolderName').val(storage["ModelFolderName"]);
    $('#txtFolderPath').val(storage["FolderPath"]);
    $("#dataBaseName").val(storage["dataBaseName"]);
    bindType();

    var provider = $("#DataType option:selected").data("provider");
    var listConnect = dicConnection[provider];
    var options = "";
    for (var i = 0; i < listConnect.length; i++) {
        options += '<option value=""' + (i == 0 ? " selected" : "") + '>' + listConnect[i] + '</option>';
    }
    $("#selListConnection").html(options);
    $("#connection").val(listConnect[0]);
}

function bindType() {
    //setTimeout(function () {
    //$(".SelectType").autocompleteArray([
    //    'bigint', 'binary', 'bit', 'char', 'date', 'datetime', 'datetime2', 'datetimeoffset',
    //    'decimal', 'float', 'geography', 'geometry', 'hierarchyid', 'image', 'int', 'money',
    //    'nchar', 'ntext', 'numeric', 'nvarchar', 'real', 'smalldatetime', 'smallint', 'smallmoney',
    //    'sql_variant', 'sysname', 'text', 'time', 'timestamp', 'tinyint', 'uniqueidentifier',
    //    'varbinary', 'varchar', 'xml'
    //], {
    //        delay: 10,
    //        minChars: 0,
    //        matchSubset: 1,
    //        width: 400, //提示的宽度
    //        scrollHeight: 300, //提示的高度
    //        // onItemSelect:selectItem,
    //        // onFindValue:findValue,
    //        autoFill: true,
    //        maxItemsToShow: 10
    //    });
    //}, 500);
}
var editors = {};
var editorsConfig = [{ id: 'EditorCreateTable', language: 'sql' },
    { id: 'EditorBuildEntity', language: 'csharp' },
    { id: 'EditorBuildDto', language: 'csharp' },
    { id: 'EditorBuildController', language: 'csharp' },
    { id: 'EditorBuildBLL', language: 'csharp' },
    { id: 'EditorBuildInterface', language: 'csharp' },
    { id: 'EditorBuildEditHTML', language: 'html' },
    { id: 'EditorBuildEditJS', language: 'javascript' },
    { id: 'EditorBuildListHtml', language: 'html' },
    { id: 'EditorBuildListJS', language: 'javascript' },
    //{ id: 'EditorBuildDal', language: 'csharp' },
    //{ id: 'EditorBuildEntityViewData', language: 'csharp' }
];
function createVue(data) {
    applist = new Vue({
        el: "#app"
        , data: {
            tableList: data,
            fieldList: [nullField]
        }
        , created: function () { }
        , methods: {
            init: function () { },
            getTableInfo: function (tableName, tablecomment, e) {
                var element = $(e.currentTarget);
                $('.list-group-item').removeClass('active');
                element.addClass('active');
                $('#txtTableName').val(tableName.toUpperCase());
                var entityName = tableName.substr(tableName.indexOf('_') + 1);
                //entityName = entityName.substr(0, 1) + entityName.substr(1).toLowerCase();
                $('#txtEntityName').val(entityName);
                $('#txtTableComment').val(tablecomment);
                storage["SearchText"] = $("#txtSearch").val();

                if (storage[tableName] && storage[tableName].length > 0) {
                    applist.fieldList = JSON.parse(storage[tableName]);
                    toastr.options.onclick = function () {
                        storage.removeItem(tableName);
                    }
                    toastr['warning']("单击清除缓存", tableName + " 表已加载缓存数据!");
                    return;
                }
                $.getJSON('/Home/GetTableDetail?TableName=' + tableName, function (fieldData) {
                    applist.fieldList = fieldData;
                    bindType();
                });
            },
            addRow: function (index) {
                applist.fieldList.splice(index + 1, 0, {
                    IsCheck: true,
                    IsDataColumn: true,
                    TypeName: ''
                });
            },
            delRow: function (index) {
                applist.fieldList.splice(index, 1);
            },
            appendRow: function (index) {
                var name = applist.fieldList[index].ColumnName;
                var comment = applist.fieldList[index].Comment;
                var IsHave = false;
                applist.fieldList.forEach(function (item) {
                    if (item.ParentName != null && name == item.ParentName) {
                        IsHave = true;
                        return;
                    }
                });
                if (IsHave) { toastr['error']("该字段 已存在扩展字段!"); return; }
                if (name.indexOf('ID') >= 0) {
                    applist.fieldList.push({
                        IsCheck: true,
                        ParentName: name,
                        ColumnName: name.substr(0, name.length - 2) + 'Name',
                        Comment: comment.substr(0, comment.length - 2) + '名称',
                        TypeName: 'nvarchar'
                    });
                } else {
                    toastr['error']("只有列名中含有“ID” 才可追加扩展字段");
                }

            },
            getPropertyName: function () {
                console.log(this);
                return this.ColumnName.substr(0, 1) + this.ColumnName.substr(1).toLowerCase();
            }
        }, filters: {},
        computed: {
            computerArr: function () {
                var arr = applist.fieldList;
                return arr.filter(function (item) {
                    return $.trim(item.ColumnName).length > 0;
                });
            },
        },
        mounted() {
            $(editorsConfig).each(function (index,item) {
                var editor = ace.edit(item.id);
                //设置风格和语言（更多风格和语言，请到github上相应目录查看）
                editor.setTheme("ace/theme/" + "monokai");
                editor.session.setMode("ace/mode/" + item.language);
                ace.require("ace/ext/language_tools");
                //字体大小
                editor.setFontSize(13);
                //设置只读（true时只读，用于展示代码）
                editor.setReadOnly(false);
                //自动换行,设置为off关闭
                editor.setOption("wrap", "free")
                editor.setOptions({
                    enableBasicAutocompletion: true,
                    enableSnippets: true,
                    enableLiveAutocompletion: true
                });
                editors[item.id] = editor;
            });
        }
    });
}


function setData(action) {
    var ConfigInfo = {
        TableName: $.trim($('#txtTableName').val()),
        TableComment: $.trim($('#txtTableComment').val()),
        ModelFolderName: $.trim($('#txtModelFolderName').val()),
        EntityName: $.trim($('#txtEntityName').val()),
        PageName: $.trim($('#txtPageName').val()),
        ControllerName: $.trim($('#txtControllerName').val()),
        FolderPath: $.trim($('#txtFolderPath').val()),
        EventName: action
    };
    //var isVer = ['BuildEntity', 'CreateTable'].indexOf(action) >= 0;//不需要判断
    //var flag = true;
    //if (ConfigInfo.TableName.length <= 0) {
    //    toastr['error']("TableName 为空")
    //    flag = false;
    //}
    //if (ConfigInfo.ModelFolderName.length <= 0 && !isVer) {
    //    toastr['error']("ModelFolderName 为空")
    //    flag = false;
    //} else {
    //    storage["ModelFolderName"] = ConfigInfo.ModelFolderName;
    //    storage["FolderPath"] = ConfigInfo.FolderPath;
    //}
    //if (!isVer && ConfigInfo.PageName.length <= 0) {
    //    toastr['error']("PageName 为空")
    //    flag = false;
    //}
    //if (!flag) { return; }
    storage[ConfigInfo.TableName] = JSON.stringify(applist.computerArr);
    var data = applist.computerArr;
    flag = false;
    //data.forEach(function (item, index) {
    //    if (item.Comment.length <= 0) {
    //        toastr['error']("第" + (index + 1) + "行 注释 为空！");
    //        flag = true;
    //    }
    //    if (item.TypeName.indexOf('char') >= 0 && item.MaxLength.length <= 0) {
    //        toastr['error']("第" + (index + 1) + "行 长度 为空！");
    //        flag = true;
    //    }
    //});
    //if (flag) { return; };
    var url = "/Home/GenerateCode";
    $.ajax({
        url: url,
        type: 'post',
        data: JSON.stringify({ DataList: data, ConfigInfo: ConfigInfo }),
        contentType: 'application/json',
        success: function (text) {
            editors["Editor" + action].setValue(text);
            setTimeout(function () {
                editors["Editor" + action].gotoLine(1);
            }, 500);
        }
    });
}
//刷新读取PDM
function refresh() {
    $.post('/Home/RefreshPdmTable', {  }, function (data) {
        refreshList();
    })
}
function fileSubmit() {
    if (check()) {
        $("form#uploadfie").ajaxSubmit({
            url: "/Home/UploadFile",
            dataType:'json',
            success: function (res) {
                if (res.status == "Success") {
                    toastr['success']("上传成功！");
                } else {
                    toastr['warning'](res.message);
                }
            }
        });
    }
}
function check() {
    var file = document.getElementById("pdmFile").value;
    if (file == "") {
        toastr['warning']("请选择文件");
        return false;
    }
    var strTemp = file.split(".");
    var strCheck = strTemp[strTemp.length - 1];
    if (strCheck.toLowerCase() == 'pdm') {
        return true;
    } else {
        toastr['warning']("请上传pdm文件！");
        return false;
    }
}
//单击 表名 文本框 从缓存 获取数据
function getDB() {
    applist.fieldList = JSON.parse(storage[$('#txtTableName').val()]);
    toastr['warning']("单击清除缓存", $('#txtTableName').val() + " 表已加载缓存数据!");
};

//刷新 表 列表数据
function refreshList() {
    $.getJSON('/Home/GetTableList', function (data) {
        applist.tableList = data;
        //列表渲染有一定的延迟，需要等待
        setTimeout(function () {
            $('#txtSearch').change();
        },300);
        toastr['success']("列表已刷新！");
    })
}


function iframeBuildMenuSQl() {
    var menuid = $('#txtMenuID').val();
    if (menuid.length > 0) {
        document.getElementById('iframeBuildMenuSQl').src = '/Home/BuildMenuSql?id=' + menuid;
    }
}
function checkConnect(){
    $.post("/Home/CheckConnection", { dataType: $("#DataType").val(), connection: $("#connection").val() }, function (data) {
        if (data == "连接成功") {
            toastr['success'](data);
        } else {
            toastr['warning']("连接失败！", data);
        }
    });
}
function setConnect() {
    $.post('/Home/SetConnection', { dataType: $("#DataType").val(), connection: $("#connection").val(), dataBaseName: $("#dataBaseName").val() }, function (data) {
        if (data == "设置成功") {
            toastr['success']("设置成功!");
            refreshList();
            storage["dataBaseName"] = $("#dataBaseName").val();
        } else {
            toastr['warning']("设置成功！", data);
        }
    })
}
function changeDataType() {
    var provider = $("#DataType option:selected").data("provider");
    if (provider == "System.Data.OracleClient") {
        $("#dataBaseName").show();
    } else {
        $("#dataBaseName").hide();
    }
    var listConnect = dicConnection[provider];
    var options = "";
    for (var i = 0; i < listConnect.length; i++) {
        options += '<option value=""' + (i == 0 ? " selected" : "") + '>' + listConnect[i] + '</option>';
    }
    $("#selListConnection").html(options);
    changeConnect();
}
function changeConnect() {
    $("#connection").val($("#selListConnection option:selected").text());
    $("#connection").focus();
}